from django.shortcuts import render, redirect
from rest_framework.response import Response
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from rest_framework.views import APIView
# 导入model
from myapp.models import User
import requests
from myapp.myser import *
from django.views import View
# 导入json
import json



import redis

# 定义ip地址和端口
host = '127.0.0.1'
port = 6379

# 定义链接对象
r = redis.Redis(host=host, port=port)


# 注册模块
class RegisterPro(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', 'null')
        password = request.GET.get('password', 'null')




        # 排重
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '该用户名已经存在'
            return Response(res)


        # 入库
        user = User(username=username, password=password)
        user.save()

        res = {}
        res['code'] = 200
        res['message'] = '注册成功'

        return Response(res)
import jwt

import base64
import hmac
from hashlib import sha256
import urllib
import time
from urllib import parse

# 钉钉第三方登录
def dingding_back(request):
    # 获取code
    code = request.GET.get("code")

    t = time.time()

    timestamp = str((int(round(t * 1000))))
    appSecret = 'rDsIHGCcvj8wgd12KCafOUEwA2Vm8Uh9uhnvhvohwxwfXxGkwd86DLpR3d7n0McG'

    # 构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'),digestmod=sha256).digest())

    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type':'application/json'}

    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoas0flvw1koxnmk1fa",data=json.dumps(payload), headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)
    # return HttpResponse(res.text)
    ding_nick = res_dict['user_info']['nick']


    user = User.objects.filter(username=ding_nick).first()

    user_id = ''

    if user:
        ding_nick = user.username
        user_id = user.id

    else:
        # 手动创建账号
        user = User(username=str(ding_nick),password='')
        user.save()

        # 查询一下刚刚入库的新账号id
        user = User.objects.filter(username=str(ding_nick)).first()
        user_id = user.id

    return redirect("http://localhost:8080?ding_nick=" + str(ding_nick)+"&uid="+str(user_id))







# 登录模块
class LoginPro(APIView):
    def get(self, request):
        # 获取用户名和密码
        username = request.GET.get('username')
        password = request.GET.get('password')

        # 打印是否取出值
        print(username, password)

        # 查询用户
        user = User.objects.filter(username=username, password=password).first()

        # 判断
        if user:
            return Response({
                'code': 200,
                'message': '登陆成功',
                'username':user.username,
                'uid':user.id

            })

        return Response({
            'code': 405,
            'message': '用户名或密码错误'
        })

from django.utils.deprecation import MiddlewareMixin

# 自定义中间件类
# class MyMiddleWare(MiddlewareMixin):
#     def process_request(self, request):
#
#         uid = request.GET.get('uid')
#         clinet_jwt = request.GET.get('jwt',None)
#
#         decode_jwt = jwt.decode(clinet_jwt, '123', algorithms=['HS256'])
#         if decode_jwt['uid'] != str(uid):
#
#             return HttpResponse('你没有带上令牌')


# 装饰器
def my_decorator(func):
    def wrapper(request,*args,**kwargs):
        #
        # # 判断jwt逻辑
        # uid = request.GET.get('uid')
        # clinet_jwt = request.GET.get('jwt','None')
        #
        # decode_jwt = jwt.decode(clinet_jwt,'123',algorithms=['HS256'])
        # if decode_jwt['uid'] != str(uid):
        #     return HttpResponse('你篡改了用户ID')
        return func(request, *args, **kwargs)

    return wrapper


# 类装饰器调用
from django.utils.decorators import method_decorator


# 用户信息
class MyInfo(APIView):
    # @method_decorator(my_decorator)
    def get(self, request):
        uid = request.GET.get('uid')

        # 查询数据
        user = User.objects.get(id=int(uid))

        # 序列化对象
        user_ser = UserSer(user)

        return Response(user_ser.data)




# 定义七牛云存储接口
from qiniu import Auth

class QiNiuPro(APIView):
    def get(self,request):

        # 定义密钥
        q = Auth('BNJACqPq8b6i9Ljsp5pSc2y8gPrlh1qtKfvaX9-i','4UmG7vDrwM9Hs5DZftTlGXySuFl27P6yhzSmtQXo')

#         指定上传空间
        token = q.upload_token('1906b')

        print(token)

        res = {}


        res['token'] = token

        return Response(res)








# 添加商品
class Addgood(APIView):
    def get(self, request):
        name = request.GET.get('name', 'null')
        desc = request.GET.get('desc', 'null')
        parms = request.GET.get('parms', 'null')
        cate_id = request.GET.get('cate_id', 'null')
        price = request.GET.get('price', 'null')

        # 排重
        good = Good.objects.filter(name=name).first()

        if good:
            res = {}
            res['code'] = 405
            res['message'] = '该商品已存在'
            return Response(res)


        r.set('parms', parms)
        # 入库操作
        good = Good(name=name, desc=desc, cate_id=cate_id, price=price, parms=parms)
        good.save()


        # 查询商品id
        good = Good.objects.filter(name=name).first()

        res = {}
        res['code'] = 200
        res['message'] = '商品添加成功'
        res['id'] = good.id
        return Response(res)




# 商品展示分页
class GoodAll(APIView):
    def get(self,request):

        # 当前页
        page = int(request.GET.get('page',1))
        # 一页有多少条商品
        size = int(request.GET.get('size',1))

        # 定义从哪开始切
        data_start = (page-1) * size

        # 定义切到哪
        data_end = page * size

        # 查询数据
        goodslist = Good.objects.all()[data_start:data_end]

        # 查询总数量
        count = Good.objects.count()

        # 序列化操作
        good_ser = GoodSer(goodslist,many=True)

        res = {}
        res['total'] = count
        res['data'] = good_ser.data
        return Response(res)





import pymongo

# 建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost',port=27017)



# 导入bson
from bson import json_util as jsonb
class GetTags(View):

    def get(self,request):

        id = request.GET.get('id',None)

        # 建立数据库对象
        db = mongo_client.md
        # 建立表对象
        table = db.mytag

        # 查询数据
        res = table.find_one({'gid':str(id)})

        # ensure_ascii=False 防止中文乱码
        return HttpResponse(jsonb.dumps(res,ensure_ascii=False))




# mongo库操作
# 商品标签添加接口
class AddTags(APIView):

    def get(self,request):
        id = request.GET.get('id',None)
        tags = request.GET.get('tags',None)
        tags = tags.split(",")



        # 建立数据库对象
        db = mongo_client.md
        # 建立表对象
        table = db.mytag

        # 排重操作
        # 查询
        res = table.find({'gid':str(id)}).count()

        if res>0:
            return Response({'message':'重复数据'})
        else:
            # 入库操作
            table.insert({'gid':str(id),"tags":tags})


            return Response({'message':'入库成功'})

# 导入原生sql模块
from django.db import connection



# 对结果集美化方法
def dictfetchall(cursor):

    # 获取游标描述
    desc = cursor.description

    return [
        dict(zip( [col[0] for col in desc],row))

        for row in cursor.fetchall()
    ]



#商品关注接口(查询用户关注过的商品列表)
class UFlow(View):
	def get(self,request):

		uid = request.GET.get("uid",None)

		#建立游标对象
		cursor = connection.cursor()

		#执行sql语句
		cursor.execute('select a.id,a.name,a.create_time from good a left join flow b on a.id = b.gid where b.uid = %s ' % str(uid))

		#获取结果
		#result = cursor.fetchall()
		result = dictfetchall(cursor)

		#返回结果 手动序列化
		return HttpResponse(json.dumps(result,ensure_ascii=False,indent=4,default=str),content_type='application/json')

from myapp.models import Flow

# 关注商品接口(取关)
class GFlow(APIView):

    def get(self, request):

        id = request.GET.get("id", None)
        uid = request.GET.get("uid", None)
        type = request.GET.get("type", 1)

        # 限制用户刷屏操作
        redis_flow = r.get(uid)
        if redis_flow:
            return Response({
                'code':400,
                'message': '请稍后操作'
            })

        if int(type) == 1:

            # 关注
            flow = Flow(gid=int(id), uid=int(uid))
            try:
                flow.save()
                message = "关注成功"
                good = Good.objects.filter(id=int(id)).first()
                good.flow = good.flow + 1
                good.save()
                # redis保存当前用户操作
                r.set(uid, '28')
                # 设置时间为180秒
                r.expire(uid, 180)
            except Exception as e:
                print(str(e))
                message = "不能重复关注"
                pass

        elif int(type) == 0:
            # 取关
            Flow.objects.filter(gid=int(id), uid=int(uid)).delete()
            message = "取关成功"
            good = Good.objects.filter(id=int(id)).first()
            good.flow = good.flow - 1
            good.save()
            # redis保存当前用户操作
            r.set(uid,'28')
            # 设置时间为180秒
            r.expire(uid,180)


        else:
            # 批量取关
            ids = request.GET.get("ids", None)
            # 批量操作
            Flow.objects.filter(uid=int(uid)).delete()
            # 强转
            id_list = eval(ids)

            for id in id_list:
                flow = Flow(gid=int(id), uid=int(uid))
                flow.save()
                # redis保存当前用户操作
                r.set(uid, '28')
                # 设置时间为180秒
                r.expire(uid, 180)

            message = "关注成功"

        return Response({'message': message})











